package servlet;

import org.apache.commons.codec.digest.DigestUtils;
import service.WxServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;

@WebServlet(name = "WxServlet", value = "/WxServlet")
public class WxServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
        signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        timestamp	时间戳
        nonce	随机数
        echostr	随机字符串
         */
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        /*
        1）将token、timestamp、nonce三个参数进行字典序排序
        2）将三个参数字符串拼接成一个字符串进行sha1加密
        3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
         */
        String[] strs=new String[]{"Golxen",timestamp,nonce};
        Arrays.sort(strs);

        String str=strs[0]+strs[1]+strs[2];
        String sign = DigestUtils.sha1Hex(str);
        if(sign.equals(signature)){
            PrintWriter out=response.getWriter();
            out.print(echostr);
            out.flush();
            out.close();
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
//        wxService wxService=new wxService();
        Map<String,String> map= WxServiceImpl.parseRequest(request.getInputStream());
        String respXML= WxServiceImpl.getRespose(map);
        PrintWriter out=response.getWriter();
        out.print(respXML);
        out.flush();
        out.close();

    }
}
